package controller;

import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import model.Schedule;
import model.Station;
import model.Train;

import org.primefaces.event.RowEditEvent;

import service.ScheduleService;

@ManagedBean
@SessionScoped
public class ScheduleController {

	@EJB
	private ScheduleService scheduleService;
	

	private List<Schedule> allSchedules = null;

	private Schedule schedule;

	public Schedule getSchedule() {
		if (schedule == null) {
			schedule = new Schedule();
			return schedule;
		} else {
			return schedule;
		}
	}

	private String station1 = "";
	private String station2 = "";
	private String train = "";

	public List<Schedule> getAllSchedules() {
		if (allSchedules == null) {
			allSchedules = scheduleService.findAll();
			return allSchedules;
		} else {
			return allSchedules;
		}
	}

	public void onEdit(RowEditEvent event) {
		Schedule editSchedule = (Schedule) event.getObject();
		System.out.println(editSchedule.getTrain().getTrainNumber());
		Schedule temp = scheduleService.findById(editSchedule.getScheduleID());
		String result = scheduleService.update(temp, editSchedule);
		allSchedules = scheduleService.findAll();
		FacesMessage msg = new FacesMessage(result);
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public void deleteSchedule(Schedule schedule) {
		scheduleService.delete(schedule);
		allSchedules = scheduleService.findAll();
	}

	public void createSchedule() {
		schedule.setStation1(new Station());
		schedule.setStation2(new Station());
		schedule.setTrain(new Train());
		schedule.getStation1().setStationName(station1);
		schedule.getStation2().setStationName(station2);
		schedule.getTrain().setTrainNumber(Integer.parseInt(train));
		String result = scheduleService.save(this.schedule);
		this.schedule = null;
		allSchedules = scheduleService.findAll();
		FacesMessage msg = new FacesMessage(result);
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public String getStation2() {
		return station2;
	}

	public void setStation2(String station2) {
		this.station2 = station2;
	}

	public String getTrain() {
		return train;
	}

	public void setTrain(String train) {
		this.train = train;
	}

	public String getStation1() {
		return station1;
	}

	public void setStation1(String station1) {
		this.station1 = station1;
	}
}
